import React, { useState, useEffect, useMemo } from 'react';
import { Card, Row, Col, Statistic, DatePicker, Select, Button, Table, Space, message } from 'antd';
import { ProCard } from '@ant-design/pro-components';
import {
  UserOutlined,
  TeamOutlined,
  RiseOutlined,
  DownloadOutlined,
  ReloadOutlined
} from '@ant-design/icons';
import dayjs from 'dayjs';
import { EchartsLine, EchartsColumn, EchartsPie, EchartsArea } from '@/components/Charts';
import {
  getUserStatistics,
  getUserGrowthTrend,
  getUserActivityStats,
  getUserDistributionStats,
  exportStatisticsData
} from '@/services/statisticsApi';

const { RangePicker } = DatePicker;
const { Option } = Select;

// 简单的图表占位符组件
const ChartPlaceholder: React.FC<{ title: string; height?: number }> = ({ title, height = 300 }) => (
  <div
    style={{
      height,
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      border: '1px dashed #d9d9d9',
      borderRadius: '6px',
      backgroundColor: '#fafafa',
      color: '#999'
    }}
  >
    {title} 图表 (开发中)
  </div>
);

const UserStats: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [timeRange, setTimeRange] = useState<STATISTICS.TimeRange>('month');
  const [dateRange, setDateRange] = useState<[dayjs.Dayjs, dayjs.Dayjs]>([
    dayjs().subtract(30, 'day'),
    dayjs()
  ]);
  const [statistics, setStatistics] = useState<STATISTICS.UserStatistics | null>(null);

  // 获取统计数据
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const params: STATISTICS.StatisticsQueryParams = {
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        granularity: 'day'
      };

      const response = await getUserStatistics(params);
      if (response.code === 200) {
        setStatistics(response.data);
      } else {
        message.error(response.message || '获取统计数据失败');
      }
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
      message.error('获取统计数据失败');
    } finally {
      setLoading(false);
    }
  };

  // 导出数据
  const handleExport = async (type: 'excel' | 'csv' | 'pdf') => {
    try {
      const params: STATISTICS.ExportParams = {
        type,
        data_type: 'user',
        time_range: timeRange,
        start_date: dateRange[0].format('YYYY-MM-DD'),
        end_date: dateRange[1].format('YYYY-MM-DD'),
        include_charts: true
      };

      await exportStatisticsData(params);
      message.success(`${type.toUpperCase()}文件导出成功`);
    } catch (error) {
      console.error('导出失败:', error);
      message.error('导出失败');
    }
  };

  useEffect(() => {
    fetchStatistics();
  }, [timeRange, dateRange]);

  // 用户增长趋势图配置
  const userGrowthConfig = useMemo(() => ({
    data: statistics?.user_growth_chart || [],
    xField: 'date',
    yField: 'value',
    smooth: true,
    point: {
      size: 3,
      shape: 'circle',
    },
    tooltip: {
      formatter: (datum: any) => ({
        name: '新增用户',
        value: `${datum.value}人`,
      }),
    },
    color: '#1890ff',
  }), [statistics?.user_growth_chart]);

  // 角色分布饼图配置
  const roleDistributionConfig = useMemo(() => ({
    data: statistics?.role_distribution || [],
    angleField: 'count',
    colorField: 'role',
    radius: 0.8,
    label: {
      type: 'outer',
      content: '{name}: {percentage}',
    },
    interactions: [{ type: 'element-active' }],
  }), [statistics?.role_distribution]);

  // 状态分布柱状图配置
  const statusDistributionConfig = useMemo(() => ({
    data: statistics?.status_distribution || [],
    xField: 'status',
    yField: 'count',
    color: '#52c41a',
    columnWidthRatio: 0.6,
    meta: {
      status: { alias: '用户状态' },
      count: { alias: '用户数量' },
    },
  }), [statistics?.status_distribution]);

  // 活跃用户表格列配置
  const activeUsersColumns = [
    {
      title: '用户ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      width: 120,
    },
    {
      title: '学习时长(小时)',
      dataIndex: 'total_study_time',
      key: 'total_study_time',
      width: 120,
      render: (time: number) => (time / 3600).toFixed(1),
    },
    {
      title: '练习次数',
      dataIndex: 'practice_count',
      key: 'practice_count',
      width: 100,
    },
    {
      title: '最后登录',
      dataIndex: 'last_login_at',
      key: 'last_login_at',
      width: 150,
      render: (time: string) => dayjs(time).format('YYYY-MM-DD HH:mm'),
    },
  ];

  return (
    <div style={{ padding: '24px' }}>
      {/* 页面标题和操作栏 */}
      <ProCard
        title="用户统计"
        extra={
          <Space>
            <Select
              value={timeRange}
              onChange={setTimeRange}
              style={{ width: 120 }}
            >
              <Option value="today">今天</Option>
              <Option value="yesterday">昨天</Option>
              <Option value="week">本周</Option>
              <Option value="month">本月</Option>
              <Option value="quarter">本季度</Option>
              <Option value="year">本年</Option>
              <Option value="custom">自定义</Option>
            </Select>
            {timeRange === 'custom' && (
              <RangePicker
                value={dateRange}
                onChange={(dates) => dates && setDateRange(dates)}
                format="YYYY-MM-DD"
              />
            )}
            <Button
              icon={<ReloadOutlined />}
              onClick={fetchStatistics}
              loading={loading}
            >
              刷新
            </Button>
            <Button.Group>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('excel')}
              >
                导出Excel
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('csv')}
              >
                导出CSV
              </Button>
              <Button
                icon={<DownloadOutlined />}
                onClick={() => handleExport('pdf')}
              >
                导出PDF
              </Button>
            </Button.Group>
          </Space>
        }
        style={{ marginBottom: 24 }}
      />

      {/* 概览统计卡片 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="总用户数"
              value={statistics?.overview.total_users || 0}
              prefix={<TeamOutlined />}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="活跃用户"
              value={statistics?.overview.active_users || 0}
              prefix={<UserOutlined />}
              valueStyle={{ color: '#52c41a' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="今日新增"
              value={statistics?.overview.new_users_today || 0}
              prefix={<RiseOutlined />}
              valueStyle={{ color: '#fa8c16' }}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card>
            <Statistic
              title="增长率"
              value={statistics?.overview.growth_rate || 0}
              suffix="%"
              prefix={<RiseOutlined />}
              valueStyle={{ 
                color: (statistics?.overview.growth_rate || 0) >= 0 ? '#52c41a' : '#ff4d4f' 
              }}
            />
          </Card>
        </Col>
      </Row>

      {/* 图表区域 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {/* 用户增长趋势 */}
        <Col xs={24} lg={16}>
          <ProCard title="用户增长趋势" loading={loading}>
            <EchartsLine {...userGrowthConfig} height={300} />
          </ProCard>
        </Col>

        {/* 角色分布 */}
        <Col xs={24} lg={8}>
          <ProCard title="用户角色分布" loading={loading}>
            <EchartsPie {...roleDistributionConfig} height={300} />
          </ProCard>
        </Col>
      </Row>

      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        {/* 用户状态分布 */}
        <Col xs={24} lg={12}>
          <ProCard title="用户状态分布" loading={loading}>
            <EchartsColumn {...statusDistributionConfig} height={300} />
          </ProCard>
        </Col>

        {/* 等级分布 */}
        <Col xs={24} lg={12}>
          <ProCard title="用户等级分布" loading={loading}>
            <EchartsPie
              data={statistics?.level_distribution || []}
              angleField="count"
              colorField="level"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              height={300}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 活跃用户排行榜 */}
      <Row gutter={[16, 16]} style={{ marginBottom: 24 }}>
        <Col xs={24}>
          <ProCard title="活跃用户排行榜" loading={loading}>
            <Table
              columns={activeUsersColumns}
              dataSource={statistics?.top_active_users || []}
              rowKey="id"
              pagination={{
                pageSize: 10,
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total) => `共 ${total} 条记录`,
              }}
              scroll={{ x: 800 }}
            />
          </ProCard>
        </Col>
      </Row>

      {/* 注册来源分析 */}
      <Row gutter={[16, 16]}>
        <Col xs={24} lg={12}>
          <ProCard title="注册来源分析" loading={loading}>
            <EchartsPie
              data={statistics?.registration_sources || []}
              angleField="count"
              colorField="source"
              radius={0.8}
              label={{
                type: 'outer',
                content: '{name}: {percentage}',
              }}
              interactions={[{ type: 'element-active' }]}
              height={300}
            />
          </ProCard>
        </Col>

        {/* 用户活跃度趋势 */}
        <Col xs={24} lg={12}>
          <ProCard title="用户活跃度趋势" loading={loading}>
            <EchartsLine
              data={statistics?.activity_stats?.daily_active_users || []}
              xField="date"
              yField="value"
              smooth={true}
              color="#52c41a"
              point={{
                size: 3,
                shape: 'circle',
              }}
              tooltip={{
                formatter: (datum: any) => ({
                  name: '日活跃用户',
                  value: `${datum.value}人`,
                }),
              }}
              height={300}
            />
          </ProCard>
        </Col>
      </Row>
    </div>
  );
};

export default UserStats;
